package com.example.wilson.lesson13;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import java.util.Calendar;

public class MainActivity extends Activity implements OnClickListener {

    private static MainActivity appRef = null;
    private Button b_call_service, b_exit_service;
    boolean k = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appRef = this;
        setContentView(R.layout.activity_main);

        b_call_service = (Button)findViewById(R.id.call_alarm_service);
        b_call_service.setOnClickListener(this);
        b_exit_service = (Button)findViewById(R.id.exit);
        b_exit_service.setOnClickListener(this);
        setTitle("123");
        
    }

    public static MainActivity getApp(){
        return appRef;
    }

    public void btEvent(String data){
        setTitle(data);
    }

    @Override
    public void onClick(View view) {
        if(view == b_call_service){
            setTitle("稍等一下，警报信号为5");
            Intent intent = new Intent(MainActivity.this, AlarmRecevier.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 3);
            //
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), p_intent);
        }

        if(view == b_exit_service){
            Intent intent = new Intent(MainActivity.this, AlarmRecevier.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.cancel(p_intent);
            finish();
        }
    }
}
